package site.marqstree.kotlin.usercenter.ui.activity.register

import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_register.*
import org.jetbrains.anko.toast
import site.marqstree.kotlin.library.base.common.AppManager
import site.marqstree.kotlin.library.base.extent.enable
import site.marqstree.kotlin.library.base.ui.activity.BaseMvpActivity
import site.marqstree.kotlin.usercenter.R
import site.marqstree.kotlin.usercenter.injection.component.DaggerUserComponent
import site.marqstree.kotlin.usercenter.presenter.view.RegisterPresenter
import javax.inject.Inject

class RegisterActivity @Inject constructor(): BaseMvpActivity<RegisterPresenter>(),
    RegisterView,
    View.OnClickListener {

    private var pressTime:Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        initView()
    }

    private fun initView() {

        mRegisterBtn.enable(mMobileEt,{isBtnEnable()})
        mRegisterBtn.enable(mVerifyCodeEt,{isBtnEnable()})
        mRegisterBtn.enable(mPwdEt,{isBtnEnable()})
        mRegisterBtn.enable(mPwdConfirmEt,{isBtnEnable()})

        mRegisterBtn.setOnClickListener(this)
        mVerifyCodeBtn.setOnClickListener(this)
    }

    override fun initBusinessInjection() {
      DaggerUserComponent
                .builder()
                .activityComponent(activityComponent)
                .build()
                .inject(this)

            //初始化View层对象，也就是当前Activity
            //View层负责UI刷新
            mPresenter.mView = this
    }

    override fun onRegisterResult(result: Boolean) {
        toast("注册成功")
        finish()
    }

    override fun onBackPressed() {
        val time = System.currentTimeMillis()
        if( time - pressTime > 2000){
            toast("再按一次退出程序")
            pressTime = time
        } else {
            AppManager.instance.exitApp(this)
        }
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.mVerifyCodeBtn->{
                mVerifyCodeBtn.requestSendVerifyNumber()
            }
            R.id.mRegisterBtn->{
                mPresenter.register(mMobileEt.text.toString(),
                        mPwdEt.text.toString(),
                        mVerifyCodeEt.text.toString())
            }
        }
    }

    /*
    判断按钮是否可用
    */
    private fun isBtnEnable():Boolean{
        return mMobileEt.text.isNullOrEmpty().not() &&
                mVerifyCodeEt.text.isNullOrEmpty().not() &&
                mPwdEt.text.isNullOrEmpty().not()&&
                mPwdConfirmEt.text.isNullOrEmpty().not()
    }
}
